--------------------------------------------------------------------
-- MACHINE A SOUS - ROCKET CASINO (3 rouleaux)
-- Se branche sur ta banque existante (client_solde.lua / banque_serveur.lua)
-- et reutilise ton systeme de login (login.lua).
--
-- PREREQUIS DANS LE MEME DOSSIER :
--   - login.lua
--   - client_solde.lua
--   - ce fichier (machine_a_sous.lua)
-- + un modem (filaire/sans-fil) active sur ce computer, relie au
--   computer qui fait tourner banque_serveur.lua
-- + un Advanced Monitor connecte a ce computer
--
-- FONCTIONNEMENT :
--   - Ecran de repos : banniere "ROCKET CASINO" avec Poke Ball qui tourne
--   - Toucher le moniteur -> login (pseudo + mot de passe) -> jeu plein ecran
--   - Bouton "QUITTER" en jeu -> retour a la banniere de repos
--------------------------------------------------------------------

local bank = dofile("client_solde.lua")
local login = dofile("login.lua")

-------------------------------
-- CONFIGURATION RAPIDE
-------------------------------
local TEXT_SCALE     = 0.5
local FRAME_DELAY     = 0.1
local ROTATION_SPEED  = 0.22
local SUBTITLE_TEXT   = "   *** PREPARE FOR TROUBLE * MAKE IT DOUBLE ***   BIENVENUE AU ROCKET CASINO   *** LES JACKPOTS SONT (PRESQUE) GARANTIS ***   "
local BET_MIN, BET_MAX, BET_STEP = 10, 1000, 10
local BET_DEFAULT = 10

math.randomseed(os.epoch and os.epoch("utc") or os.time())

-------------------------------
-- INITIALISATION DU MONITEUR
-------------------------------
local mon = peripheral.find("monitor")
if not mon then
  error("Aucun moniteur trouve ! Connecte un Advanced Monitor a cet ordinateur.", 0)
end

mon.setTextScale(TEXT_SCALE)
mon.setBackgroundColor(colors.black)
mon.clear()

local W, H = mon.getSize()

-------------------------------
-- OUTILS DE DESSIN BAS NIVEAU (canvas pixel + blit)
-------------------------------

local function newCanvas(bg)
  local c = {}
  for y = 1, H do
    c[y] = {}
    for x = 1, W do
      c[y][x] = { bg = bg, ch = " ", fg = colors.white }
    end
  end
  return c
end

local function px(canvas, x, y, bg, ch, fg)
  x, y = math.floor(x + 0.5), math.floor(y + 0.5)
  if x >= 1 and x <= W and y >= 1 and y <= H then
    local cell = canvas[y][x]
    if bg then cell.bg = bg end
    if ch then
      cell.ch = ch
      cell.fg = fg or cell.fg
    end
  end
end

local function render(canvas)
  local toBlit = colors.toBlit
  for y = 1, H do
    local row = canvas[y]
    local chars, fgs, bgs = {}, {}, {}
    for x = 1, W do
      local cell = row[x]
      chars[x] = cell.ch
      fgs[x] = toBlit(cell.fg)
      bgs[x] = toBlit(cell.bg)
    end
    mon.setCursorPos(1, y)
    mon.blit(table.concat(chars), table.concat(fgs), table.concat(bgs))
  end
end

-------------------------------
-- PRIMITIVES DE FORMES
-------------------------------

local function fillEllipse(canvas, cx, cy, rx, ry, color)
  if rx <= 0 or ry <= 0 then return end
  for y = math.floor(cy - ry), math.ceil(cy + ry) do
    local dy = (y - cy) / ry
    local t = 1 - dy * dy
    if t >= 0 then
      local dx = rx * math.sqrt(t)
      for x = math.floor(cx - dx), math.ceil(cx + dx) do
        px(canvas, x, y, color)
      end
    end
  end
end

local function fillRect(canvas, x1, y1, x2, y2, color)
  for y = y1, y2 do
    for x = x1, x2 do
      px(canvas, x, y, color)
    end
  end
end

-- Triangle pointant vers le haut (base en bas, tip en haut)
local function fillTriangleUp(canvas, cx, baseY, tipY, halfWidth, color)
  local height = baseY - tipY
  if height <= 0 then return end
  for y = tipY, baseY do
    local f = (y - tipY) / height
    local w = halfWidth * f
    for x = math.floor(cx - w), math.ceil(cx + w) do
      px(canvas, x, y, color)
    end
  end
end

-- Triangle pointant vers le bas (base en haut, tip en bas)
local function fillTriangleDown(canvas, cx, baseY, tipY, halfWidth, color)
  local height = tipY - baseY
  if height <= 0 then return end
  for y = baseY, tipY do
    local f = (tipY - y) / height
    local w = halfWidth * f
    for x = math.floor(cx - w), math.ceil(cx + w) do
      px(canvas, x, y, color)
    end
  end
end

-- Triangle horizontal (base a baseX, tip a tipX)
local function fillTriangleSide(canvas, baseX, tipX, cy, halfHeight, color)
  local width = tipX - baseX
  if width == 0 then return end
  local step = width > 0 and 1 or -1
  for x = baseX, tipX, step do
    local f = (x - baseX) / width
    local hh = halfHeight * (1 - f)
    for y = math.floor(cy - hh), math.ceil(cy + hh) do
      px(canvas, x, y, color)
    end
  end
end

-------------------------------
-- MINI POLICE PIXEL 5x7
-------------------------------

local FONT = {
  R = { "####.", "#...#", "#...#", "####.", "#..#.", "#...#", "#...#" },
  O = { ".###.", "#...#", "#...#", "#...#", "#...#", "#...#", ".###." },
  C = { ".####", "#....", "#....", "#....", "#....", "#....", ".####" },
  K = { "#...#", "#..#.", "#.#..", "##...", "#.#..", "#..#.", "#...#" },
  E = { "#####", "#....", "#....", "####.", "#....", "#....", "#####" },
  T = { "#####", "..#..", "..#..", "..#..", "..#..", "..#..", "..#.." },
  A = { ".###.", "#...#", "#...#", "#####", "#...#", "#...#", "#...#" },
  S = { ".####", "#....", "#....", ".###.", "....#", "....#", "####." },
  I = { "#####", "..#..", "..#..", "..#..", "..#..", "..#..", "#####" },
  N = { "#...#", "##..#", "#.#.#", "#..##", "#...#", "#...#", "#...#" },
  L = { "#....", "#....", "#....", "#....", "#....", "#....", "#####" },
  ["7"] = { "#####", "....#", "...#.", "..#..", ".#...", ".#...", ".#..." },
}

local function drawGlyph(canvas, pattern, x0, y0, scale, color)
  for row = 1, #pattern do
    local line = pattern[row]
    for col = 1, #line do
      if line:sub(col, col) == "#" then
        for sy = 0, scale - 1 do
          for sx = 0, scale - 1 do
            px(canvas, x0 + (col - 1) * scale + sx, y0 + (row - 1) * scale + sy, color)
          end
        end
      end
    end
  end
end

local function drawText(canvas, x, y, text, fg, bg)
  for i = 1, #text do
    px(canvas, x + i - 1, y, bg, text:sub(i, i), fg)
  end
end

-- Dessine un bouton tactile " LABEL " et l'enregistre dans la liste buttons.
-- Retourne la position x suivante (pour enchainer plusieurs boutons).
local function drawButton(canvas, buttons, id, x, y, label, bg, fg)
  local text = " " .. label .. " "
  for i = 1, #text do
    px(canvas, x + i - 1, y, bg, text:sub(i, i), fg or colors.white)
  end
  table.insert(buttons, { id = id, x1 = x, x2 = x + #text - 1, y1 = y, y2 = y })
  return x + #text
end

-------------------------------
-- BANNIERE / ELEMENTS COMMUNS
-------------------------------

local CHASE_COLORS = { colors.yellow, colors.orange, colors.red, colors.orange }
local function drawMarquee(canvas, tick)
  local n = #CHASE_COLORS
  for x = 1, W do
    local c = CHASE_COLORS[((x + tick) % n) + 1]
    px(canvas, x, 1, c)
    px(canvas, x, H, c)
  end
  for y = 1, H do
    local c = CHASE_COLORS[((y + tick) % n) + 1]
    px(canvas, 1, y, c)
    px(canvas, W, y, c)
  end
end

-- Grand titre pixel-art generique (2 mots). redIdx1/redIdx2 = index de la
-- lettre a colorer en rouge dans chaque mot (nil = pas de lettre rouge).
-- Retourne la ligne Y juste sous le titre.
local ACCENT_COLORS = { colors.yellow, colors.orange, colors.white, colors.orange }
local function drawBigTitle(canvas, tick, word1, word2, redIdx1, redIdx2)
  local LETTER_W, GAP_W, WORD_GAP = 5, 1, 4

  local function wordUnits(word)
    return #word * LETTER_W + (#word - 1) * GAP_W
  end
  local totalUnits = wordUnits(word1) + WORD_GAP + wordUnits(word2)

  local scale = math.max(1, math.floor((W - 6) / totalUnits))
  local totalWidth = totalUnits * scale
  local startX = math.max(2, math.floor((W - totalWidth) / 2) + 1)
  local startY = 3

  local accent = ACCENT_COLORS[(math.floor(tick / 3) % #ACCENT_COLORS) + 1]

  local function drawWord(word, x, redLetterIndex)
    for i = 1, #word do
      local letter = word:sub(i, i)
      local pattern = FONT[letter]
      local color = (redLetterIndex and i == redLetterIndex) and colors.red or accent
      if pattern then
        drawGlyph(canvas, pattern, x + 1, startY + 1, scale, colors.black)
        drawGlyph(canvas, pattern, x, startY, scale, color)
      end
      x = x + (LETTER_W + GAP_W) * scale
    end
    return x
  end

  local cursor = startX
  cursor = drawWord(word1, cursor, redIdx1)
  cursor = cursor + (WORD_GAP - GAP_W) * scale
  drawWord(word2, cursor, redIdx2)

  return startY + 7 * scale + 2
end

local function drawSubtitle(canvas, tick)
  local y = H - 2
  local len = #SUBTITLE_TEXT
  local offset = tick % len
  local scrolled = SUBTITLE_TEXT:sub(offset + 1) .. SUBTITLE_TEXT:sub(1, offset)
  local visible = scrolled:sub(1, math.max(0, W - 4))
  drawText(canvas, 3, y, visible, colors.yellow, colors.black)
end

-- Poke Ball : palette inversee (noir en haut / rouge en bas) qui tourne.
-- angle = 0 -> vue de face fixe (utilise pour le symbole de la machine a sous)
local function drawPokeball(canvas, cx, cy, r, angle)
  local squish = math.max(0.12, math.abs(math.cos(angle)))
  local rx = r * squish
  local ry = r

  fillEllipse(canvas, cx, cy, rx + 1.2, ry + 1.2, colors.gray)

  for y = math.floor(cy - ry), math.ceil(cy + ry) do
    local dy = (y - cy) / ry
    local t = 1 - dy * dy
    if t >= 0 then
      local dx = rx * math.sqrt(t)
      local color
      if y < cy - ry * 0.08 then
        color = colors.black
      elseif y > cy + ry * 0.08 then
        color = colors.red
      else
        color = colors.lightGray
      end
      for x = math.floor(cx - dx), math.ceil(cx + dx) do
        px(canvas, x, y, color)
      end
    end
  end

  for x = math.floor(cx - rx), math.ceil(cx + rx) do
    px(canvas, x, cy, colors.black)
  end

  local buttonR = math.max(1, r * 0.28 * squish)
  fillEllipse(canvas, cx, cy, buttonR + 0.6, buttonR + 0.6, colors.black)
  fillEllipse(canvas, cx, cy, buttonR, buttonR, colors.white)
  fillEllipse(canvas, cx, cy, buttonR * 0.5, buttonR * 0.5, colors.lightGray)

  if squish > 0.55 then
    local scale = math.max(1, math.floor(r * squish / 5))
    local rx0 = math.floor(cx - 2 * scale)
    local ry0 = math.floor(cy - ry * 0.75)
    for dx = -1, 1 do
      for dy = -1, 1 do
        if dx ~= 0 or dy ~= 0 then
          drawGlyph(canvas, FONT.R, rx0 + dx, ry0 + dy, scale, colors.black)
        end
      end
    end
    drawGlyph(canvas, FONT.R, rx0, ry0, scale, colors.red)
  end
end

-------------------------------
-- SYMBOLES DE LA MACHINE A SOUS (dessins originaux)
-------------------------------

local function drawSymbolSeven(canvas, cx, cy, r)
  fillEllipse(canvas, cx, cy, r, r, colors.black)
  fillEllipse(canvas, cx, cy, r * 0.85, r * 0.85, colors.red)
  local scale = math.max(1, math.floor(r / 4))
  drawGlyph(canvas, FONT["7"], math.floor(cx - 2.5 * scale), math.floor(cy - 3.5 * scale), scale, colors.yellow)
end

local function drawSymbolStar(canvas, cx, cy, r)
  fillTriangleUp(canvas, cx, cy, cy - r, r * 0.22, colors.yellow)
  fillTriangleDown(canvas, cx, cy, cy + r, r * 0.22, colors.yellow)
  fillTriangleSide(canvas, cx, cx - r, cy, r * 0.22, colors.yellow)
  fillTriangleSide(canvas, cx, cx + r, cy, r * 0.22, colors.yellow)
  fillEllipse(canvas, cx, cy, r * 0.2, r * 0.2, colors.white)
end

local function drawSymbolFlame(canvas, cx, cy, r)
  fillEllipse(canvas, cx, cy + r * 0.15, r * 0.7, r * 0.6, colors.red)
  fillTriangleUp(canvas, cx, cy + r * 0.15, cy - r, r * 0.55, colors.red)
  fillEllipse(canvas, cx, cy + r * 0.25, r * 0.45, r * 0.4, colors.orange)
  fillTriangleUp(canvas, cx, cy + r * 0.25, cy - r * 0.55, r * 0.32, colors.orange)
  fillEllipse(canvas, cx, cy + r * 0.35, r * 0.2, r * 0.2, colors.yellow)
end

local function drawSymbolCoin(canvas, cx, cy, r)
  fillEllipse(canvas, cx, cy, r, r, colors.brown)
  fillEllipse(canvas, cx, cy, r * 0.8, r * 0.8, colors.orange)
  fillEllipse(canvas, cx, cy, r * 0.55, r * 0.55, colors.yellow)
  px(canvas, cx, cy, colors.brown)
end

local function drawSymbol(canvas, id, cx, cy, r)
  if id == "BALL" then
    drawPokeball(canvas, cx, cy, r, 0)
  elseif id == "SEVEN" then
    drawSymbolSeven(canvas, cx, cy, r)
  elseif id == "STAR" then
    drawSymbolStar(canvas, cx, cy, r)
  elseif id == "FLAME" then
    drawSymbolFlame(canvas, cx, cy, r)
  elseif id == "COIN" then
    drawSymbolCoin(canvas, cx, cy, r)
  end
end

-------------------------------
-- TABLE DES GAINS
-------------------------------

local SYMBOLS = {
  { id = "BALL",  weight = 1, mult = 20 },
  { id = "SEVEN", weight = 2, mult = 10 },
  { id = "STAR",  weight = 3, mult = 7 },
  { id = "FLAME", weight = 4, mult = 5 },
  { id = "COIN",  weight = 5, mult = 3 },
}

local TOTAL_WEIGHT = 0
for _, s in ipairs(SYMBOLS) do TOTAL_WEIGHT = TOTAL_WEIGHT + s.weight end

local MULT_BY_ID = {}
for _, s in ipairs(SYMBOLS) do MULT_BY_ID[s.id] = s.mult end

local function pickSymbol()
  local roll = math.random(TOTAL_WEIGHT)
  local acc = 0
  for _, s in ipairs(SYMBOLS) do
    acc = acc + s.weight
    if roll <= acc then return s.id end
  end
  return SYMBOLS[#SYMBOLS].id
end

local function evaluateWin(symbols, bet)
  if symbols[1] == symbols[2] and symbols[2] == symbols[3] then
    local mult = MULT_BY_ID[symbols[1]] or 1
    return bet * mult, "JACKPOT ! 3x " .. symbols[1] .. " (x" .. mult .. ")"
  elseif symbols[1] == symbols[2] or symbols[2] == symbols[3] or symbols[1] == symbols[3] then
    return bet, "Petit gain, mise remboursee !"
  else
    return 0, "Perdu... retente ta chance !"
  end
end

-------------------------------
-- ECRAN DE LA MACHINE A SOUS
-------------------------------

local function drawSlotScreen(tick, player, credit, bet, symbols, message)
  local canvas = newCanvas(colors.black)
  local buttons = {}

  drawMarquee(canvas, tick)
  local contentTop = drawBigTitle(canvas, tick, "ROCKET", "SLOTS", 1, nil)

  local info = "Joueur: " .. player .. "   Solde: " .. credit .. "   Mise: " .. bet
  local infoX = math.max(2, math.floor((W - #info) / 2) + 1)
  drawText(canvas, infoX, contentTop, info, colors.white, colors.black)

  local reelsY = contentTop + 2
  local reelH = math.max(4, math.floor(H * 0.28))
  local reelW = math.max(4, math.floor(W * 0.2))
  local gap = math.max(1, math.floor(W * 0.04))
  local totalW = reelW * 3 + gap * 2
  local startX = math.max(2, math.floor((W - totalW) / 2) + 1)

  for i = 1, 3 do
    local x1 = startX + (i - 1) * (reelW + gap)
    local x2 = x1 + reelW
    local y1 = reelsY
    local y2 = reelsY + reelH
    fillRect(canvas, x1 - 1, y1 - 1, x2 + 1, y2 + 1, colors.black)
    fillRect(canvas, x1, y1, x2, y2, colors.lightGray)
    local cx = math.floor((x1 + x2) / 2)
    local cy = math.floor((y1 + y2) / 2)
    local symR = math.max(1, math.floor(math.min(reelW, reelH) * 0.42))
    drawSymbol(canvas, symbols[i], cx, cy, symR)
  end

  local msgY = reelsY + reelH + 2
  local msgX = math.max(2, math.floor((W - #message) / 2) + 1)
  drawText(canvas, msgX, msgY, message, colors.yellow, colors.black)

  local btnY = H - 2
  local cursor = 3
  cursor = drawButton(canvas, buttons, "BET_DOWN", cursor, btnY, "-MISE", colors.red, colors.white)
  cursor = cursor + 1
  cursor = drawButton(canvas, buttons, "BET_UP", cursor, btnY, "+MISE", colors.green, colors.white)
  cursor = cursor + 2
  cursor = drawButton(canvas, buttons, "SPIN", cursor, btnY, "TOURNER", colors.orange, colors.black)
  cursor = cursor + 2
  drawButton(canvas, buttons, "QUIT", cursor, btnY, "QUITTER", colors.gray, colors.white)

  render(canvas)
  return buttons
end

-- Animation des rouleaux : ils s'arretent l'un apres l'autre (suspense).
-- Retourne le resultat final (3 symboles).
local function spinAnimation(player, creditDuringSpin, bet)
  local finalSymbols = { pickSymbol(), pickSymbol(), pickSymbol() }
  local stopTimes = { 1.0, 1.6, 2.2 }
  local dt = 0.08
  local t = 0
  local current = { pickSymbol(), pickSymbol(), pickSymbol() }

  while t < stopTimes[3] + 0.2 do
    for i = 1, 3 do
      if t < stopTimes[i] then
        current[i] = pickSymbol()
      else
        current[i] = finalSymbols[i]
      end
    end
    drawSlotScreen(math.floor(t * 10), player, creditDuringSpin, bet, current, "Ca tourne...")
    sleep(dt)
    t = t + dt
  end

  return finalSymbols
end

-------------------------------
-- SESSION DE JEU (login + boucle de jeu)
-------------------------------

local function runGameSession()
  local previousTerm = term.current()
  term.redirect(mon)
  local player = login.authenticate("Qui joue au Rocket Casino ?")
  term.redirect(previousTerm)

  local bet = BET_DEFAULT
  local symbols = { "COIN", "COIN", "COIN" }
  local message = "Place ta mise et lance les rouleaux !"
  local tick = 0
  local running = true

  while running do
    local credit = bank.getBalance(player)
    local buttons = drawSlotScreen(tick, player, credit, bet, symbols, message)
    tick = tick + 1

    local _, _, x, y = os.pullEvent("monitor_touch")
    local pressed = nil
    for _, btn in ipairs(buttons) do
      if x >= btn.x1 and x <= btn.x2 and y >= btn.y1 and y <= btn.y2 then
        pressed = btn.id
        break
      end
    end

    if pressed == "BET_DOWN" then
      bet = math.max(BET_MIN, bet - BET_STEP)
      message = "Mise : " .. bet
    elseif pressed == "BET_UP" then
      bet = math.min(BET_MAX, bet + BET_STEP)
      message = "Mise : " .. bet
    elseif pressed == "SPIN" then
      local balance = bank.getBalance(player)
      if balance < bet then
        message = "Solde insuffisant pour cette mise !"
      else
        local newBal, err = bank.addBalance(player, -bet)
        if not newBal then
          message = err or "Erreur banque, reessaie."
        else
          symbols = spinAnimation(player, newBal, bet)
          local gain, resultMsg = evaluateWin(symbols, bet)
          if gain > 0 then
            bank.addBalance(player, gain)
          end
          message = resultMsg
        end
      end
    elseif pressed == "QUIT" then
      running = false
    end
  end
end

-------------------------------
-- BANNIERE DE REPOS + BOUCLE PRINCIPALE
-------------------------------

local function drawIdleFrame(tick, angle)
  local canvas = newCanvas(colors.black)
  drawMarquee(canvas, tick)
  local contentTop = drawBigTitle(canvas, tick, "ROCKET", "CASINO", 1, 1)

  local centerX = math.floor(W / 2)
  local availableH = math.max(6, (H - 3) - contentTop)
  local centerY = contentTop + math.floor(availableH / 2)
  local shapeR = math.floor(math.min(W * 0.22, availableH * 0.45))
  drawPokeball(canvas, centerX, centerY, shapeR, angle)

  local hint = "*** TOUCHE L'ECRAN POUR JOUER ***"
  local hx = math.max(2, math.floor((W - #hint) / 2) + 1)
  drawText(canvas, hx, math.min(H - 4, centerY + shapeR + 2), hint, colors.white, colors.black)

  drawSubtitle(canvas, tick)
  render(canvas)
end

local function idleLoop()
  local tick, angle = 0, 0
  while true do
    drawIdleFrame(tick, angle)
    angle = angle + ROTATION_SPEED
    tick = tick + 1
    sleep(FRAME_DELAY)
  end
end

local function waitForTouch()
  os.pullEvent("monitor_touch")
end

while true do
  parallel.waitForAny(idleLoop, waitForTouch)
  runGameSession()
end
